package com.alan.wifishare.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

/**
 * @ClassName:  FileMd5   
 * @Description:  获取文件或字符串的MD5值，注意：获取文件的MD5值时，文件太大会相当耗时
 * @author: Alan.wang  
 * @date:   2014-10-16 15:05  
 * version:1.0.0
 */ 
public class Md5Util {
	
    private static final char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
    	'a', 'b', 'c', 'd', 'e', 'f' };

    /**
     * 传入文件路径，获取文件的MD5值
     * @param fileUrl
     * @return
     */
    public static String getFileMd5(String fileUrl) {
    	InputStream is;
		try {
			is = new FileInputStream(fileUrl);
			return getFileMd5(is);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
    }
    
    /**
     * 传入文件输入流，获取文件的MD5值
     * @param is
     * @return
     */
    public static String getFileMd5(InputStream is) {
    	if (is != null) {
    		byte[] buffer = new byte[1024];
            int len = 0;
    		try {
    			MessageDigest md5 = MessageDigest.getInstance("MD5");
                while((len = is.read(buffer)) > 0) {
                    md5.update(buffer, 0, len);
                }
                is.close();
                return byteToMd5(md5.digest());  
    		} catch (NoSuchAlgorithmException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    			return null;
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    			return null;
    		}
		}else {
			return null;
		}
    }
    

    /**
     * 将byte字符数组转化成MD5
     * @param b
     * @return
     */
    public static String byteToMd5(byte[] b) {
        StringBuilder sb = new StringBuilder(b.length * 2);
        for (int i = 0; i < b.length; i++) {
            sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);
            sb.append(HEX_DIGITS[b[i] & 0x0f]);
        }
        return sb.toString();
    }
    
    /**
     * 获取字符串的MD5值
     * @param key
     * @return
     */
    public static String stringToMd5(String key) {
    	try {
			return byteToMd5(MessageDigest.getInstance("MD5").digest(key.getBytes("UTF-8")));
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
    }
    
}
